<!--
 * @Descripttion: 根据销售单退货
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-11 20:19:30
 -->
<template>
  <div class="bill_container">
    <affix>
      <div class="clearfix paddingLR20">
        <div class="oper-button btn-group fr">
          <el-button type="default" @click="btnJump2List">历史单据</el-button>
          <el-button type="primary" :loading="btnLoading.save" @click="btnSaveData">保存(Ctrl+S)</el-button>
        </div>
      </div>
    </affix>
    <el-main>
      <el-form
        ref="billForm"
        :model="dataObj"
        :rules="ruleValidator"
        label-position="left"
        inline
        label-width="80px"
      >
        <el-card shadow="never">
          <div slot="header" class="header clearfix">
            <div class="clearfix index_container form">
              <div class="fr">
                <el-form-item class="bill-number font12 white-border" label="单据编号: " prop="billNo">
                  <el-input v-model="dataObj.billNo" class="w150" size="mini" />
                </el-form-item>
              </div>
            </div>
            <div class="index_container title">
              <h1> 销售退货单 </h1>
            </div>
          </div>
          <div class="clearfix font12 paddingB10">
            <div class="fl">
              <el-button type="primary" @click="btnReSelect">重选销售单</el-button>
              <!-- <el-checkbox v-model="dataObj.isPrint" label="保存后打印" border /> -->
              <span>
                销售单编号: <a>{{ dataObj.purchasebillNo }}</a>
                <!-- <el-link></el-link> -->
              </span>
            </div>
            <div class="fr">
              <span>经手人 : {{ dataObj.handUserName }}</span>
              <span class="margin-l10">业务日期 : {{ dataObj.businessTime }}</span>
            </div>
          </div>
          <ShowGoodsList ref="GoodsSelect" />
          <div class="bottom">
            <table class="table" border="1" cellspacing="0" cellpadding="0">
              <tr>
                <td align="right" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <div class="w300">
                    <el-form-item label="其他费用:" prop="amountOther">
                      {{ dataObj.amountOther }}
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item label="结算账户:" prop="accountId" style="width:100%">
                    <SelectAccount
                      v-model="dataObj.accountId"
                    />
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td align="right">
                  <div class="w200">
                    <el-form-item label="总金额:" prop="amountPaid">
                      {{ dataObj.amountPayable }}
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item label="实退金额:" prop="amountPaid">
                    <el-input v-model.number="dataObj.amountPaid" />
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td style="padding:0;" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <table class="wfull" border="0" cellspacing="0" cellpadding="0">
                    <tr class="lastrow">
                      <td width="100">
                        备 注:
                      </td>
                      <td class="lastCol">
                        <el-input v-model="dataObj.remarks" class="wfull" type="textarea" />
                      </td>
                    </tr>
                  </table>
                </td>
                <td :width="tableFixedWidth" style="padding:0; position: relative; overflow: hidden;">
                  <el-button class="full-button" type="primary" :loading="btnLoading.save" @click="btnSaveData">保存(Ctrl+S)</el-button>
                </td>
              </tr>
            </table>
          </div>
        </el-card>
      </el-form>
      <el-dialog
        title="选择销售单"
        width="90%"
        height="90%"
        :visible.sync="isShowList"
        destroy-on-close
        append-to-body
      >
        <PurchaseList operation="select" @on-select="onSelect" />
      </el-dialog>
    </el-main>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import { amount } from '@/libs/tools.js'
import { update } from './mixins'
import Affix from '@/components/Affix'
import { ShowGoodsList } from '@/views/bill/common'
import SelectAccount from '@/views/components/SelectAccount'
import PurchaseList from '@/views/bill/purchase/purchase/list.vue'
import { addSaleReturn } from '@/api/bill/bill-sale-return.js'
import clonedeep from 'clonedeep'

export default {
  name: 'SaleReturnAddHasRelation',
  components: { Affix, ShowGoodsList, SelectAccount, PurchaseList },
  filters: {
    goodAmount: function(row) {
      return amount(row.price).multiply(row.num).format()
    }
  },
  mixins: [update, oftenuse],
  props: {
    billId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      optionsData: { account: [] },
      isShowList: false,
      tableFixedWidth: 300,
      goodsSelectComp: null,
      ruleValidator: {
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ],
        amountPaid: [
          { validator: (rule, value, callback) => {
            const amountPayable = this.dataObj.amountPayable
            if (value > amountPayable) return callback(new Error(`金额不能大于${amountPayable}`))
            callback()
          } }
        ]
      }
    }
  },
  computed: {
    totalMsg: function() {
      const GoodsSelect = this.goodsSelectComp
      if (!GoodsSelect) return {}
      return GoodsSelect.totalMsg
    }
  },
  watch: {
    'totalMsg': {
      handler(data) {
        const price = data.price || '0.00'
        this.$set(this.dataObj, 'amountPayable', price)
        this.$set(this.dataObj, 'amountPaid', price)
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.goodsSelectComp = this.$refs.GoodsSelect
  },
  created() {
    this.initData()
  },
  methods: {
    btnReSelect() {
      this.isShowList = true
    },
    btnJump2List() {
      this.$router.push({
        name: 'PurchaseList'
      })
    },
    btnSaveData() {
      this.handleVali().then(_ => {
        const billDetailList = clonedeep(this.$refs.GoodsSelect.getPostData())
        const bill = clonedeep(this.dataObj)
        if (billDetailList.length === 0) return this.$message.error('请选择销售商品！')
        const params = { bill, billDetailList }
        this.setBtnLoading('save', true)
        this.saveData(params).then((res) => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) return
          this.jump2List()
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    initData() {
      this.initTransData()
    },
    handleVali() {
      const v1 = this.handleValid('billForm')
      const v2 = this.$refs.GoodsSelect.valiData()
      return Promise.all([v1, v2])
    },
    saveData(params) {
      return new Promise((resolve, reject) => {
        addSaleReturn(params).then(res => {
          resolve(res)
          if (!res.data.flag) return
          this.$notify.success({ title: '保存成功！' })
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err || '' })
          reject(err)
        })
      })
    },
    jump2AddDetail() {
      this.$router.push({
        name: 'SalereturnAddNoRelation'
      })
    },
    jump2List() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'SaleReturnList',
        params: { refresh: true }
      })
    },
    // on
    onSelect(row) {
      this.isShowList = false
      const { id } = row
      this.$router.push({
        name: 'PurchasereturnAddHasRelation',
        query: { billId: id }
      })
    },
    onTdMouseEnter(e) {
      const target = e.target
      target.className = 'bg-gay'
    },
    onTdMouseLeave(e) {
      const target = e.target
      target.className = ''
    }
  }
}
</script>
